package com.keter.framework.web.component.http;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 框架提供Http客户端组件
 * Created by gulixing@msn.com on 2018/12/18.
 */
@Component
public class HttpClienter {
    public final static int CONNECTION_TIMEOUT = 2 * 1000;
    public final static int DEFAULT_READ_TIMEOUT_SEC = 10 * 1000;
    /**
     * 提供基于HttpComponents实现的RestTemplate
     *
     * @return
     */
    public RestTemplate restTemplate() {
        return restTemplate(DEFAULT_READ_TIMEOUT_SEC);
    }

    public RestTemplate restTemplate(int READ_TIMEOUT_SEC) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)      //设置连接超时
                .readTimeout(READ_TIMEOUT_SEC, TimeUnit.SECONDS)         //设置读超时
                .writeTimeout(60, TimeUnit.SECONDS)        //设置写超时
                .retryOnConnectionFailure(true)            //是否自动重连
                .connectionPool(
                        new ConnectionPool(
                                10,    // 10个并发连接
                                6,       // 6分钟空闲自动回收
                                TimeUnit.MINUTES))
                .build();
        // 使用OkHttp3构造restTemplate客户端
        return new RestTemplate(new OkHttp3ClientHttpRequestFactory(client));
    }
}
